package com.muse.interceptor;

import com.google.gson.Gson;
import com.muse.app.service.UserService;
import com.muse.constant.Constant;
import com.muse.entity.Result;
import com.muse.entity.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    private static final List<String> APP_SKIP_LIST = Stream.of(
            "/muse/login",
            "/muse/login/sendSmsCode",
            "/manage/login"
    ).collect(Collectors.toList());


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        return true;
        boolean isSkip = false;
        String uri = request.getRequestURI();

        if (APP_SKIP_LIST.contains(uri)) {
            isSkip = true;
        }

        if (isSkip) {
            return true;
        } else {
            //需要登录的接口
            boolean auth = false;
            String token = request.getHeader("Authorization");
            if (token != null) {
                UserInfo userInfo = userService.getUserByToken(token);
                if (token.startsWith(Constant.MANAGE_TOKEN) && uri.startsWith(Constant.MANAGE_URI_START_WITH)) {
                    //后台管理登录
                    if (userInfo != null && userInfo.getManageRole() == 0) {
                        responseFailed(response, "无权登录！", 403);
                        return false;
                    }
                }
                if (userInfo != null) {
                    userInfo.setToken(token);
                    CurrentContext.set(userInfo);
                    auth = true;
                }
            }
            if (auth) {
                return true;
            } else {
                responseFailed(response, "当前用户未登录!", 401);
                return false;
            }
        }
    }

    private void responseFailed(HttpServletResponse response, String msg, int status) {
        response.setCharacterEncoding("UTF-8");
        response.setStatus(status);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");

        PrintWriter out = null;
        Result<Map<String, Object>> result = new Result<>();
        Gson g = new Gson();
        result.setStatus(1);
        result.setMsg(msg);

        try {
            out = response.getWriter();
            out.write(g.toJson(result));
        } catch (IOException e) {
            log.error("LoginInterceptor response error", e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) {
    }

    @Override


    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) {
        // 请求结束后清空ThreadLocal中的user对象
        CurrentContext.set(null);
    }
}